/**   
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-07 13:44:19  
 * Copyright (c) 2015- joysuch-版权所有     
 */

package com.joysuch.wwyt.bp.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import com.joysuch.wwyt.bp.bean.BpEmergencyMaterialTypeEditBean;
import com.joysuch.wwyt.bp.bean.BpEmergencyMaterialTypeListBean;
import com.joysuch.wwyt.bp.bean.BpEmergencyMaterialTypeListBean.Search;
import com.joysuch.wwyt.bp.entity.BpEmergencyMaterialType;
import com.joysuch.wwyt.bp.repository.BpEmergencyMaterialTypeDao;
import com.joysuch.wwyt.bp.service.BpEmergencyMaterialTypeService;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.querydsl.core.types.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class BpEmergencyMaterialTypeServiceImpl implements BpEmergencyMaterialTypeService {

    @Autowired
    private BpEmergencyMaterialTypeDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;

    @Override
    public BpEmergencyMaterialType add(BpEmergencyMaterialTypeEditBean entity) throws Exception {
        BpEmergencyMaterialType content = new BpEmergencyMaterialType();
        // 物资类型名称
        content.setName(entity.getName());
        // 物资数
        content.setMaterialCount(0);
        return dao.save(content);
    }

    @Override
    public void update(BpEmergencyMaterialTypeEditBean entity) throws Exception {
        BpEmergencyMaterialType content = dao.findById(entity.getId()).get();
        // ID，主键
        content.setId(entity.getId());
        // 物资类型名称
        content.setName(entity.getName());
        // 物资数
        content.setMaterialCount(entity.getMaterialCount() == null ? 0 : entity.getMaterialCount());
        dao.save(content);
    }

    @Override
    public Page<BpEmergencyMaterialTypeListBean> findByPage(Pageable page, Search condition) {
        Predicate predicate = prepareListSearchCondition(condition);

        Page<BpEmergencyMaterialType> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);

        return PageDataUtils.convertPageData(data,
                new PageDataConvert<BpEmergencyMaterialTypeListBean, BpEmergencyMaterialType>() {

                    @Override
                    public BpEmergencyMaterialTypeListBean convert(BpEmergencyMaterialType f) {
                        BpEmergencyMaterialTypeListBean bean = new BpEmergencyMaterialTypeListBean();

                        // ID，主键
                        bean.setValue(f.getId());
                        // 物资类型名称
                        bean.setLabel(f.getName());
                        // 物资数
                        bean.setMaterialCount(f.getMaterialCount());

                        return bean;
                    }

                });
    }

    private Predicate prepareListSearchCondition(Search condition) {
        return null;
    }

    @Override
    public void delete(Long id) {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        checkBussinessRestrictions(id);
        dao.deleteById(id);
    }

    /**
     * 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用
     * 
     * @param id
     *            要删除的业务ID
     * @throws BusinessRestrictionsException
     *             抛出的业务异常
     */
    private void checkBussinessRestrictions(Long id) {

    }

    @Override
    public BpEmergencyMaterialType findById(Long id) {
        return dao.findById(id).orElse(null);
    }

    @Override
    public List<BpEmergencyMaterialTypeListBean> findAll() {
        List<BpEmergencyMaterialType> all = dao.findAll(Sort.by(Sort.Order.desc("materialCount")));
        List<BpEmergencyMaterialTypeListBean> allList = new ArrayList<>();
        for (BpEmergencyMaterialType temp : all) {
            BpEmergencyMaterialTypeListBean bean = new BpEmergencyMaterialTypeListBean();
            bean.setValue(temp.getId());
            bean.setLabel(temp.getName());
            bean.setMaterialCount(temp.getMaterialCount());
            allList.add(bean);
        }
        return allList;
    }

    @Override
    public void updateMaterialCount(Long id) {
        if (id != null) {
            dao.updateMaterialCount(id);
        }
    }

    @Override
    public boolean checkName(String name) {
        int count = dao.countByName(name);
        return count > 0 ? true : false;
    }

    @Override
    public void save(List<Map<String, Object>> materialTypeList) throws BusinessRestrictionsException {

        List<BpEmergencyMaterialTypeListBean> sourceMaterialTypeList = findAll();
        List<Long> ids = new ArrayList<>();
        for (Map<String, Object> tempMap : materialTypeList) {
            // 循环获取待操作的物资类型数组
            if (tempMap.containsKey("id")) { // 如果有 ID ，则修改
                // 记录操作过的 ID ，用于之后的删除判断
                Long tempId = Long.parseLong(tempMap.get("id").toString());
                ids.add(tempId);
                for (BpEmergencyMaterialTypeListBean tempBean : sourceMaterialTypeList) {
                    // 循环获取原物资类型对象
                    if (tempId.equals(tempBean.getValue())) {
                        // 如果该物资类型下没有物资，并且没有重复名称的物资类型，则进行修改
                        if (tempBean.getMaterialCount() <= 0 && !checkName(tempMap.get("label").toString())) {
                            // 进行修改操作
                            BpEmergencyMaterialType tempDocType = findById(tempId);
                            tempDocType.setName(tempMap.get("label").toString());
                            dao.save(tempDocType);
                        }
                    }
                }
            } else { // 没有 ID，则新增
                if (!checkName(tempMap.get("label").toString())) { // 如果物资类型名称不重复，则添加
                    // 进行添加操作
                    BpEmergencyMaterialType tempDocTypeAdd = new BpEmergencyMaterialType();
                    tempDocTypeAdd.setName(tempMap.get("label").toString());
                    tempDocTypeAdd.setMaterialCount(0);
                    dao.save(tempDocTypeAdd);
                }
            }
        }
        // 如果传入的 ID 小于 原物资类型数量，进行删除操作
        if (ids.size() < sourceMaterialTypeList.size()) {
            // 筛选出需要删除的对象
            List<BpEmergencyMaterialTypeListBean> deleteList = sourceMaterialTypeList;
            for (int i = 0; i < sourceMaterialTypeList.size(); i++) {
                for (Long itemId : ids) {
                    if (sourceMaterialTypeList.get(i).getValue().equals(itemId)) {
                        deleteList.remove(i);
                    }
                }
            }
            if (deleteList.size() > 0) {
                for (BpEmergencyMaterialTypeListBean tempDelet : deleteList) {
                    // 如果该物资类型下没有物资，则进行删除操作
                    if (tempDelet.getMaterialCount() <= 0) {
                        // 进行删除操作
                        delete(tempDelet.getValue());
                    }
                }
            }
        }
    }
}
